
//
//  WBBaseViewController.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/1.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit

//class WBBaseViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

class WBBaseViewController: UIViewController{
    
    //用户登录标记
//    var userLogin = false
    
    var visitorInfoDic:[String:String]?
    
    var tableView:UITableView?
    //刷新控件
    var refreshControl:UIRefreshControl?
    //区分上啦刷新的标记
    var isPullup = false
    
    
    lazy var navigationBar = UINavigationBar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        WBNetworkManger.shared.userLogin ? loadData() : ()
//        loadData()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
    }
    
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
    
    func loadData() {
        //如果子类不实现任何方法，默认关闭刷新控件
        refreshControl?.endRefreshing()
    }

}

// MARK: - 访客视图监听方法
extension WBBaseViewController{
   
    /// 登录成功处理
    @objc fileprivate func loginSuccess(n:Notification) {
        print("登录成功\(n)")
        //登录前左边是注册，右边是登录
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        //更新UI 将访客视图替换为表格视图
        //需要重新设置view
        //在访问view的getter时，如果view = nil会调用loadview -> viewDidLoad
        view = nil
        //注销通知->重新执行viewdidload会再次注册 避免通知被重新注册
        NotificationCenter.default.removeObserver(self)
        
    }
    
    @objc fileprivate func login(){
        print("登录")
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc fileprivate func register(){
        print("注册")
    }
}

extension WBBaseViewController{
    
    fileprivate func setupUI(){
        view.backgroundColor = UIColor.orange
            //取消自动缩进，隐藏导航栏的时候，会缩进20点
            automaticallyAdjustsScrollViewInsets = false
            setupNavigationBar()
        WBNetworkManger.shared.userLogin ? setupTableview() : setupVisiterView()
         
    }
    
    

fileprivate func setupVisiterView(){
        let visiterView = WBVisitorView(frame: view.bounds)
        
//        visiterView.backgroundColor = UIColor.red
        
        view.insertSubview(visiterView, belowSubview: navigationBar)
//        print("访客视图 \(visiterView)")
        //设置访客视图信息
        visiterView.visitorInfo = visitorInfoDic
        //设置访客视图按钮的监听方法
        visiterView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
    
        visiterView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
    
        //设置导航栏按钮
    navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(login))
    navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(register))
    
    }
    
     func setupTableview(){
        tableView = UITableView(frame: view.bounds, style: .plain)
//        view.addSubview(tableView!)
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        tableView?.dataSource = self
        tableView?.delegate = self
        
        //设置内容缩进
        tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height, 0, tabBarController?.tabBar.bounds.height ?? 49, 0)
        
        //修改指示器的缩进 强行解包为了拿到一个必有的inset
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        
        //刷新控件
        refreshControl = UIRefreshControl()
        tableView?.addSubview(refreshControl!)
        //添加监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    
    fileprivate func setupNavigationBar(){
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
        
        navigationBar.barTintColor = UIColor.white
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        //设置系统按钮的问题渲染颜色
        navigationBar.tintColor = UIColor.orange
    }
}

extension WBBaseViewController:UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    //在显示最后一行的时候，做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //1.判断indexpath是不是最后一行
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0 {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup {
            print("上啦刷新")
            isPullup = true
            //开始刷新
            loadData()
        }
//        print("section -- \(section)")
        
    }
}
